<?php


namespace app\admin\controller;

use app\admin\model\Dictionary;
use app\admin\model\Project as projectModel;
use app\admin\model\Task as TaskMode;
use app\admin\model\TaskPersonRelation;
use app\admin\service\JiraArrayConfiguration;
use app\admin\service\JiraProject;
use JiraRestApi\Issue\IssueField;
use JiraRestApi\Issue\IssueService;
use JiraRestApi\JiraException;
use Monolog\Logger;
use think\Log;
use think\Session;

class Project extends Permissions
{
    public function index()
    {
        $post = $this->request->param();
        //dump($post);
        //默认排序
        $sortWhere['project_level_sort'] = 0;
        $sortWhere['project_speed_sort'] = 0;
        $sortWhere['project_type_sort'] = 0;
        $sortWhere['current_stage_sort'] = 0;
        $sortWhere['project_manager_id_sort'] = 0;
        $sortWhere['project_status_sort'] = 0;
        $order = "p.begin_time desc";
        //选择排序
        if (isset($post['project_level_sort']) && !empty($post['project_level_sort'])) {
            if ($post['project_level_sort'] == 1) {
                $order = "p.project_level asc";
            } else {
                $order = "p.project_level desc";
            }
            $sortWhere['project_level_sort'] = $post['project_level_sort'];
        }
        if (isset($post['project_speed_sort']) && !empty($post['project_speed_sort'])) {
            if ($post['project_speed_sort'] == 1) {
                $order = "p.project_speed asc";
            } else {
                $order = "p.project_speed desc";
            }
            $sortWhere['project_speed_sort'] = $post['project_speed_sort'];
        }
        if (isset($post['project_type_sort']) && !empty($post['project_type_sort'])) {
            if ($post['project_type_sort'] == 1) {
                $order = "p.project_type asc";
            } else {
                $order = "p.project_type desc";
            }
            $sortWhere['project_type_sort'] = $post['project_type_sort'];
        }
        if (isset($post['current_stage_sort']) && !empty($post['current_stage_sort'])) {
            if ($post['current_stage_sort'] == 1) {
                $order = "p.current_stage asc";
            } else {
                $order = "p.current_stage desc";
            }
            $sortWhere['current_stage_sort'] = $post['current_stage_sort'];
        }
        if (isset($post['project_manager_id_sort']) && !empty($post['project_manager_id_sort'])) {
            if ($post['project_manager_id_sort'] == 1) {
                $order = "p.project_manager_id asc";
            } else {
                $order = "p.project_manager_id desc";
            }
            $sortWhere['project_manager_id_sort'] = $post['project_manager_id_sort'];
        }
        if (isset($post['project_status_sort']) && !empty($post['project_status_sort'])) {
            if ($post['project_status_sort'] == 1) {
                $order = "p.project_status asc";
            } else {
                $order = "p.project_status desc";
            }
            $sortWhere['project_status_sort'] = $post['project_status_sort'];
        }
        //排序咋这么一大坨呢 算了还是不改了吧

        //条件
        $where['p.is_del'] = 0;
        $project_type = $post['project_type'] ?? 0;
        $project_status = $post['project_status'] ?? 0;
        $project_stage = $post['project_stage'] ?? [];

        !empty($post['project_type']) && $where['p.project_type'] = $post['project_type'];
        !empty($post['project_status']) && $where['p.project_status'] = $post['project_status'];
        !empty($post['project_stage']) && $where['p.current_stage'] = ['in', $post['project_stage']];

        $projectModel = new projectModel();
        $project = $projectModel->alias("p")
            ->field("p.* ,a.nickname as project_manager_name")
            ->join("tplay_admin a", "a.id = p.project_manager_id", 'left')
            ->where($where)
            ->order($order)
            ->paginate(15, false, ['query' => request()->param()]);
        //echo $projectModel->getLastSql();
        $page = $project->render();
        $this->assign('page', $page);
        $this->assign("project", $project);
        $this->assign("sortWhere", $sortWhere);
        $this->assign("projetcTypeName", Dictionary::projetcTypeName());
        $this->assign("projectStageName", Dictionary::projectStageName());
        $this->assign("projectLevelMap", Dictionary::projectLevelMap());
        $this->assign("projectStatusName", Dictionary::projectStatusName());
        $this->assign("project_status", $project_status);
        $this->assign("project_stage", $project_stage);
        $this->assign("project_type", $project_type);
        return $this->fetch();
    }

    public function publish()
    {
        $id = $this->request->has('project_id') ? $this->request->param('project_id', 0, 'intval') : 0;
        $projectModel = new projectModel();
        $adminModel = new \app\admin\model\Admin();
        $personList = $adminModel->field("nickname as person_name, id as person_id")->where(["is_prd" => 0])->order(['name' => 'acs'])->select();
        if ($id > 0) {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $post['update_time'] = time();
                $post['begin_time'] = !empty($post['begin_time']) ? strtotime($post['begin_time'] . ' 00:00:00') : 0;
                $post['end_time'] = !empty($post['end_time']) ? strtotime($post['end_time'] . ' 23:59:59') : 0;
                $post['estimate_time'] = !empty($post['estimate_time']) ? strtotime($post['estimate_time'] . ' 23:59:59') : 0;
                if (!empty($post['estimate_time']) && !empty($post['begin_time'])) {
                    $post['estimate_day'] = ceil(($post['estimate_time'] - $post['begin_time']) / 24 / 3600);
                }
                $userId = Session::get('admin');
                $post['update_user_id'] = $userId;//dump($post);die;
                if (false == $projectModel->allowField(true)->save($post, ["project_id" => $id])) {
                    return $this->error('修改加项目失败');
                } else {
                    addlog('update projectId: ' . $projectModel->project_id);//写入日志
                    return $this->success('修改项目成功', 'admin/project/index');
                }
            } else {
                $info = $projectModel->where(["project_id" => $id, "is_del" => 0])->find();
            }
        } else {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                $post['create_time'] = time();
                $post['update_time'] = time();
                $post['begin_time'] = !empty($post['begin_time']) ? strtotime($post['begin_time'] . ' 00:00:00') : 0;
                $post['end_time'] = !empty($post['end_time']) ? strtotime($post['end_time'] . ' 23:59:59') : 0;
                $post['estimate_time'] = !empty($post['estimate_time']) ? strtotime($post['estimate_time'] . ' 23:59:59') : 0;
                if (!empty($post['estimate_time']) && !empty($post['begin_time'])) {
                    $post['estimate_day'] = ceil(($post['estimate_time'] - $post['begin_time']) / 24 / 3600);
                }
                $userId = Session::get('admin');
                $post['create_user_id'] = $userId;
                $post['update_user_id'] = $userId;
                //dump($post);

                //创建jira issue
                if (!empty($post['product_line']) && $post['is_create_jira'] == 'on') {
                    $projectKey = $post['product_line'];

                    $project_manager_name = $adminModel->where(['id' => $post['project_manager_id']])->find()['name'];
                    //var_dump($project_manager_name);

                    try {
                        $issueField = new IssueField();
                        $issueField->setProjectKey($projectKey)
                            ->setSummary($post['project_name'])
                            ->setAssigneeName($project_manager_name)
                            //->setPriorityName("High")//High,Medium,Low
                            ->setIssueType("项目")
                            ->setDescription($post['project_content'])
                            ->addCustomField('customfield_10002', $post['project_name'])
                            ->addCustomField('customfield_10600', ['value' => Dictionary::jiraProjectStagMap($post['current_stage'], 'jira')]);

                        $issueService = new IssueService(new JiraArrayConfiguration());
                        $ret = $issueService->create($issueField);
                        Log::info('创建jira成功了~ jira_id: ' . $ret->key);

                        $post['jira_id'] = $ret->key;
                        //dump($ret);
                        Log::log(print_r($ret, true));
                    } catch (JiraException $e) {
                        Log::error(" 创建issue失败..." . $e->getMessage() . ' 类:' . __CLASS__ . " 方法:" . __FUNCTION__ . " 行:" . __LINE__);
                    }
                }

                //die;


                if (false == $projectModel->allowField(true)->save($post)) {
                    return $this->error('添加项目失败');
                } else {
                    addlog('add projectId: ' . $projectModel->project_id);//写入日志
                    return $this->success('添加项目成功', 'admin/project/index');
                }
            } else {
                $info = null;

            }
        }
        $jiraProjectService = new JiraProject();
        $jiraProjectList = $jiraProjectService->getAllProjectList();
        $this->assign("jiraProjectList", $jiraProjectList);
        $this->assign("info", $info);
        $this->assign("personList", $personList);
        $this->assign("projetcTypeName", Dictionary::projetcTypeName());
        $this->assign("projectStageName", Dictionary::projectStageName());
        $this->assign("projectStatusName", Dictionary::projectStatusName());
        $this->assign("projectLevelMap", Dictionary::projectLevelMap());
        return $this->fetch();
    }

    /**
     * 项目删除
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $project_id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if ($project_id) {
                $projectModel = new projectModel();
                $projectInfo = $projectModel->where(['project_id' => $project_id, 'is_del' => 0])->find();
                if ($projectInfo) {

                    $taskModel = new TaskMode();
                    $taskInfos = $taskModel->where(["project_id" => $project_id, "is_del" => 0])->select();
                    foreach ($taskInfos as $taskInfo) {
                        $relationModel = new TaskPersonRelation();
                        $relation_update_date['relation_status'] = 20;//解绑
                        $relation_update_date['update_user_id'] = Session::get('admin');;
                        $relation_update_date['update_time'] = time();
                        $relationModel->where(['task_id' => $taskInfo['task_id'], 'relation_status' => 10])->update($relation_update_date);
                        $taskModel->where(["task_id" => $taskInfo['task_id'], "is_del" => 0])->update(['update_user_id' => Session::get('admin'), 'update_time' => time(), 'is_del' => 1]);
                    }
                    $projectModel->where(['project_id' => $project_id, 'is_del' => 0])->update(['update_user_id' => Session::get('admin'), 'update_time' => time(), 'is_del' => 1]);
                }
                return $this->success("删除成功!");
            }
            return $this->error('参数有误! 未查询到需要删除的项目...');
        } else {
            return $this->error("非法请求!!!");
        }
    }

    /**
     * 根据jiraId从jira系统获取issue信息
     * @throws \JsonMapper_Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getIssueInfo()
    {
        if ($this->request->isAjax()) {
            if (!$this->request->has('jira_id')) {
                return $this->error('缺少参数!');
            }
            $jira_id = $this->request->param('jira_id');
            try {
                $issueService = new IssueService();
                $queryParam = [
                    'fields' => [// default: '*all'
//                    'summary',
//                    'comment',
                    ],
                    'expand' => [
                        'renderedFields',
                        'names',
                        'schema',
                        'transitions',
                        'operations',
                        'editmeta',
                        'changelog',
                    ]
                ];

                $issue = $issueService->get($jira_id, $queryParam);

                $issue_type_name = $issue->fields->getIssueType()->name;
                $summary = $issue->fields->summary;
                if ($issue_type_name != '项目') {
                    Log::info("JIRA_ID:" . $jira_id . " 不是项目JIRA issue类型:" . $issue_type_name . " jira:" . $summary);
                    return $this->error("JIRA_ID:" . $jira_id . " 不是项目JIRA");
                }
                $assignee_name = $issue->fields->assignee->name;
                $project_manager_id = '';
                if ($assignee_name) {
                    $adminModel = new \app\admin\model\Admin();
                    $project_manager_id = $adminModel->where(['name' => $assignee_name])->find()['id'];
                }
                $data = [
                    'project_name' => $summary,
                    //经办人(项目经理)
                    'assignee_name' => $assignee_name,
                    //项目经理查找项目经理ID
                    'project_manager_id' => $project_manager_id,
                ];
                return $this->success('成功', '', $data);

            } catch (JiraException $e) {
                $error_msg = "根据JIRA_ID:" . $jira_id . " 获取项目信息失败 原因:" . $e->getMessage();
                Log::error($error_msg);
                return $this->error($error_msg);
            }


        } else {
            return $this->error("非法请求!!!");
        }
    }
}